package cn.android666.net.util.download.dialog

import android.app.Dialog
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager

class MyDialog(private val builder: DialogBuilder) : DialogFragment() {

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val alertDialog = builder.create()
        // Dialog本身的setCancelable方法无效，调用DialogFragment的setCancelable方法才有用。
        isCancelable = builder.cancelable
        return alertDialog
    }

    class DialogBuilder(context: Context) : AlertDialog.Builder(context) {

        var cancelable = true

        override fun setCancelable(cancelable: Boolean): AlertDialog.Builder? {
            this.cancelable = cancelable
            return super.setCancelable(cancelable)
        }

    }


    companion object {

        private var count = 0

        fun show(context: Context, fragmentManager: FragmentManager, tag: String? = null, init: DialogBuilder.() -> Unit) {
            val dialogTag = tag ?: "DialogTag_${count++}"

            // 不要用这个方式，当应用被切到后台时，Activity会马上调用onSaveInstanceState方法，这个方法调用后无法调用下面的方法来显示对话框
            // MyDialog(DialogBuilder(context).apply(init)).show(fragmentManager, dialogTag)

            // 使用commitAllowingStateLoss()，即使onSaveInstanceState已被调用，也可以显示对话框
            val dialog = MyDialog(DialogBuilder(context).apply(init))
            fragmentManager
                .beginTransaction()
                .add(dialog, dialogTag)
                .commitAllowingStateLoss()
        }

        fun dismiss(fragmentManager: FragmentManager, tag: String) {
            (fragmentManager.findFragmentByTag(tag) as? MyDialog)?.dismissAllowingStateLoss()
        }

    }

}